import { LIST_PAGE_PARAM_KEY, LIST_PAGESIZE_PARAM_KEY } from '@/constant'
import { memo, useEffect, useState } from 'react'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { Pagination } from 'antd'

type propType = {
  total: number
}

const ListPagination = memo((props: propType) => {
  const { total } = props
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [searchParams] = useSearchParams()
  const { pathname } = useLocation()
  const nav = useNavigate()

  const changePage = (page: number, pageSize: number) => {
    searchParams.set(LIST_PAGE_PARAM_KEY, page.toString())
    searchParams.set(LIST_PAGESIZE_PARAM_KEY, pageSize.toString())

    nav({
      pathname,
      search: searchParams.toString(),
    })
  }

  useEffect(() => {
    const pageSize = parseInt(searchParams.get(LIST_PAGESIZE_PARAM_KEY) || '') || 10
    setPageSize(pageSize)
    const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
    setCurrent(page)
  }, [searchParams])

  return <Pagination current={current} pageSize={pageSize} total={total} onChange={changePage} />
})

export default ListPagination
